package GradeManager.StudentGradeSystem.service.imp;

import GradeManager.StudentGradeSystem.utils.UpdateStudentGrade;
import GradeManager.StudentGradeSystem.dao.AccountDao;
import GradeManager.StudentGradeSystem.dao.StudentDao;
import GradeManager.StudentGradeSystem.dao.TeacherDao;
import GradeManager.StudentGradeSystem.pojo.Account;
import GradeManager.StudentGradeSystem.pojo.PageBean;
import GradeManager.StudentGradeSystem.pojo.Student;
import GradeManager.StudentGradeSystem.pojo.Teacher;
import GradeManager.StudentGradeSystem.service.TeacherService;
import GradeManager.StudentGradeSystem.utils.GetNowTime;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Iterator;
import java.util.List;

@Slf4j
@Service
public class TeacherServiceImp implements TeacherService {
    @Autowired
    private TeacherDao teacherDao;
    @Autowired
    private StudentDao studentDao;
    @Autowired
    private AccountDao accountDao;
    @Autowired
    private GetNowTime addTime;
    @Autowired
    private UpdateStudentGrade updateStudentGrade;
    @Override
    public PageBean<Teacher> initTable(int currentPage, int pageSize) {
        //分页
        IPage page=new Page(currentPage,pageSize);
        teacherDao.selectPage(page, null);
        PageBean<Teacher> pageBean=new PageBean<>();
//        设置每页信息和总条数
        pageBean.setRows(page.getRecords());
        pageBean.setTotalCount(page.getTotal());
        //返回封装好的对象
        return pageBean;
    }
    @Transactional
    @Override
    public boolean addStudentGrades(Teacher addform) {
        //记录添加成绩信息的日志
        log.info("添加的成绩信息:{}",addform);
//        获取填写的所有信息
        Float chinese=addform.getChinese();
        Float math= addform.getMath();
        Float english=addform.getEnglish();
        Integer studentId= addform.getStudentId();
        String schoolyear=addform.getSchoolYear();
        String nowTime= addTime.getNowTime();
        //查找数据库中是否已存在当前添加的信息
        LambdaQueryWrapper<Teacher> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Teacher::getSchoolYear,schoolyear)
                .eq(Teacher::getStudentId,studentId);
        Teacher rivalInfo = teacherDao.selectOne(wrapper);
//        如果已存在则添加失败
        if(rivalInfo!=null){
            return false;
        }
//        不存在则继续执行添加操作
//        根据学号获取姓名
        LambdaQueryWrapper<Account> lqw=new LambdaQueryWrapper<>();
        lqw.eq(Account::getUserId,studentId);
        String studentname=accountDao.selectOne(lqw).getUserName();
//        如果填写的成绩不为空就添加至学生表中并计算总成绩
        float totalScore=0;
        if(null!=chinese && chinese>=0 && chinese<=150){
            totalScore+=chinese;
            Student insertchinese=new Student(studentId,schoolyear,studentname,"语文",chinese,nowTime);
            studentDao.insert(insertchinese);
        }
        if(null!=math && math>=0 && math<=150){
            totalScore+=math;
            Student insertmath=new Student(studentId,schoolyear,studentname,"数学",math,nowTime);
            studentDao.insert(insertmath);
        }
        if(null!=english && english>=0 && english<=150){
            totalScore+=english;
            Student insertenglish=new Student(studentId,schoolyear,studentname,"英语",english,nowTime);
            studentDao.insert(insertenglish);
        }
        //老师表添加信息
        teacherDao.insert(new Teacher(schoolyear,studentId,studentname,chinese,math,english,totalScore));
        return true;
    }

    @Override
    public PageBean<Teacher> selectByCondition(Teacher teacherCondition, int currentPage, int pageSize) {
        log.info("教师搜索条件：{}",teacherCondition);
//        根据条件查找信息
        LambdaQueryWrapper<Teacher> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.hasLength(teacherCondition.getSchoolYear()),Teacher::getSchoolYear,teacherCondition.getSchoolYear())
                .like(teacherCondition.getStudentId()!=null,Teacher::getStudentId,teacherCondition.getStudentId())
                .like(StringUtils.hasLength(teacherCondition.getStudentName()),Teacher::getStudentName,teacherCondition.getStudentName());
//        获取结果急并封装
        List<Teacher> rows = teacherDao.selectList(wrapper);
        PageBean<Teacher> pageBean=new PageBean<>();
        pageBean.setRows(rows);
        long total=rows.size();
        pageBean.setTotalCount(total);
        return pageBean;
    }
    @Transactional
    @Override
    public void updateStudentGrades(Teacher updatedData) {
//        获取要修改的学生信息
        Integer studentId= updatedData.getStudentId();
        String schoolyear= updatedData.getSchoolYear();
        Float chinese= updatedData.getChinese();
        Float math= updatedData.getMath();
        Float english= updatedData.getEnglish();
//        查找老师表中年份和学号与修改之前相同的学生信息
        LambdaQueryWrapper<Teacher> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Teacher::getSchoolYear,updatedData.getSchoolYear())
                .eq(Teacher::getStudentId,updatedData.getStudentId());
//        获取学生原来的学生信息
        Teacher rivalInfo = teacherDao.selectOne(wrapper);
//        计算总成绩
        float totalScore=0;
        if(chinese!=null){
            totalScore+=chinese;
        }if(math!=null){
            totalScore+=math;
        }if(english!=null){
            totalScore+=english;
        }
//        封装修改后的信息
        Teacher updatedTeacherRow=new Teacher(schoolyear,studentId,rivalInfo.getStudentName(),
                chinese,math,english,totalScore);
//        记录修改后的日志并修改老师表
        log.info("修改成绩后的学生信息:{}",updatedTeacherRow);
        teacherDao.updateGrades(updatedTeacherRow);
//        获取学生名字和当前时间
        String studentname=rivalInfo.getStudentName();
        String updatetime=addTime.getNowTime();

//        如果填写的成绩不为空，则修改学生表
        Student updateChinese=new Student(studentId,schoolyear,studentname,"语文", updatedData.getChinese(), updatetime);
        Student updateMath=new Student(studentId,schoolyear,studentname,"数学", updatedData.getMath(), updatetime);
        Student updateEnglish=new Student(studentId,schoolyear,studentname,"英语", updatedData.getEnglish(), updatetime);
        updateStudentGrade.setUpdatedSubject(updateChinese);
        updateStudentGrade.update();
        updateStudentGrade.setUpdatedSubject(updateMath);
        updateStudentGrade.update();
        updateStudentGrade.setUpdatedSubject(updateEnglish);
        updateStudentGrade.update();
    }
    @Transactional
    @Override
    public void deleteStudentGrade(String schoolyear, Integer studentId) {
        //删除老师表中的成绩信息
        LambdaQueryWrapper<Teacher> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Teacher::getSchoolYear,schoolyear).eq(Teacher::getStudentId,studentId);
        teacherDao.delete(wrapper);
        //删除学生表中的成绩信息
        LambdaQueryWrapper<Student> lqw=new LambdaQueryWrapper<>();
        lqw.eq(Student::getSchoolYear,schoolyear).eq(Student::getStudentId,studentId);
        studentDao.delete(lqw);
    }

    @Override
    public void mutildelete(List<Teacher> list) {
//       遍历集合中的所有选中的记录并逐一删除
        Iterator<Teacher> iterator = list.iterator();
        while(iterator.hasNext()){
            Teacher next=iterator.next();
            String schoolYear = next.getSchoolYear();
            Integer studentId = next.getStudentId();
//            调用删除方法
            deleteStudentGrade(schoolYear,studentId);
        }
    }
}
